import React, { useState, useEffect, useRef, useCallback } from "react";
import { SpinLoading } from "antd-mobile";
import { UserOutline } from "antd-mobile-icons";

const VirtualList = ({
    data = [],
    renderItem,
    pageSize = 10,
    onLoadMore,
    onRefresh,
    hasMore = true,
    loading = false,
    loadingMore = false,
    refreshing = false,
    className = "",
    style = {},
    itemHeight = "auto",
    containerHeight = "auto",
    threshold = 0.1,
    onItemClick,
    pullToRefresh = false,
    loadMoreText = "上拉加载更多",
    loadingText = "加载中...",
    noMoreText = "没有更多内容了",
    emptyText = "暂无数据",
    errorRetry = false
}) => {
    const [currentPage, setCurrentPage] = useState(1);
    const [localData, setLocalData] = useState([]);
    const [localHasMore, setLocalHasMore] = useState(hasMore);
    const [localLoading, setLocalLoading] = useState(loading);
    const [localLoadingMore, setLocalLoadingMore] = useState(loadingMore);
    const [localRefreshing, setLocalRefreshing] = useState(refreshing);
    const [loadError, setLoadError] = useState(false);
    const [pullDistance, setPullDistance] = useState(0);
    const [isPulling, setIsPulling] = useState(false);
    
    const observerRef = useRef();
    const loadingRef = useRef();
    const containerRef = useRef();
    const startY = useRef(0);
    const currentY = useRef(0);

    // 加载更多数据
    const loadMore = useCallback(async () => {
        if (localLoadingMore || !localHasMore || localLoading) return;
        
        try {
            setLocalLoadingMore(true);
            setLoadError(false);
            
            if (onLoadMore) {
                await onLoadMore(currentPage + 1, true);
            }
            
            setCurrentPage(prev => prev + 1);
        } catch (error) {
            console.error("加载更多失败:", error);
            setLoadError(true);
        } finally {
            setLocalLoadingMore(false);
        }
    }, [localLoadingMore, localHasMore, currentPage, onLoadMore, localLoading]);

    // 下拉刷新
    const handleRefresh = useCallback(async () => {
        if (localRefreshing || localLoading) return;
        
        try {
            setLocalRefreshing(true);
            setLoadError(false);
            // 刷新时回到顶部
            if (containerRef.current) {
                try {
                    containerRef.current.scrollTop = 0;
                } catch (_) {}
            }
            
            if (onRefresh) {
                await onRefresh();
            } else if (onLoadMore) {
                // 如果没有专门的刷新函数，重新加载第一页
                await onLoadMore(1, false);
            }
            
            setCurrentPage(1);
        } catch (error) {
            console.error("刷新失败:", error);
            setLoadError(true);
        } finally {
            setLocalRefreshing(false);
            setPullDistance(0);
            setIsPulling(false);
        }
    }, [localRefreshing, localLoading, onRefresh, onLoadMore]);

    // 触摸事件处理 - 下拉刷新
    const handleTouchStart = useCallback((e) => {
        if (!pullToRefresh || localRefreshing) return;
        
        startY.current = e.touches[0].clientY;
        currentY.current = e.touches[0].clientY;
        setIsPulling(false);
    }, [pullToRefresh, localRefreshing]);

    const handleTouchMove = useCallback((e) => {
        if (!pullToRefresh || localRefreshing) return;
        
        currentY.current = e.touches[0].clientY;
        const deltaY = currentY.current - startY.current;
        
        const container = containerRef.current;
        if (!container) return;
        
        // 判断使用容器滚动还是页面滚动
        const isContainerScrollable = container.scrollHeight > container.clientHeight;
        const containerTop = container.getBoundingClientRect().top;
        const pageScrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
        // 顶部判定：
        // 1) 容器滚动：容器 scrollTop 为 0
        // 2) 页面滚动：列表顶部已贴近/越过视口顶部（允许 4px 误差）
        const isAtTop = isContainerScrollable ? (container.scrollTop <= 0) : (containerTop <= 4);
        
        // 只在顶部且向下滑动时才触发下拉
        if (isAtTop && deltaY > 0) {
            // 阻止页面继续滚动，进入下拉手势
            e.preventDefault();
            setIsPulling(true);
            // 提高灵敏度，减小阻尼；最大下拉距离 100px
            setPullDistance(Math.min(deltaY * 0.9, 100));
        }
    }, [pullToRefresh, localRefreshing]);

    const handleTouchEnd = useCallback(() => {
        if (!pullToRefresh || localRefreshing) return;
        
        if (isPulling && pullDistance >= 40) {
            handleRefresh();
        } else {
            setPullDistance(0);
            setIsPulling(false);
        }
    }, [pullToRefresh, localRefreshing, isPulling, pullDistance, handleRefresh]);

    // 设置交叉观察器
    useEffect(() => {
        const observer = new IntersectionObserver(
            (entries) => {
                if (entries[0].isIntersecting && localHasMore && !localLoadingMore) {
                    loadMore();
                }
            },
            { threshold }
        );
        
        if (loadingRef.current) {
            observer.observe(loadingRef.current);
        }
        
        observerRef.current = observer;
        
        return () => {
            if (observerRef.current) {
                observerRef.current.disconnect();
            }
        };
    }, [loadMore, localHasMore, localLoadingMore, threshold]);

    // 初次渲染或加载状态变化后，如果加载更多触发器已在视口内但因 loading 阻塞未触发，再次尝试触发
    useEffect(() => {
        if (!loadingRef.current || !localHasMore) return;
        const rect = loadingRef.current.getBoundingClientRect();
        const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
        const inView = rect.top < viewportHeight && rect.bottom > 0;
        if (inView && !localLoading && !localLoadingMore) {
            loadMore();
        }
    }, [localLoading, localLoadingMore, localHasMore, loadMore]);

    // 同步外部状态
    useEffect(() => {
        setLocalData(data);
        setLocalHasMore(hasMore);
        setLocalLoading(loading);
        setLocalLoadingMore(loadingMore);
        setLocalRefreshing(refreshing);
    }, [data, hasMore, loading, loadingMore, refreshing]);

    // 重置分页
    useEffect(() => {
        setCurrentPage(1);
    }, [data]);

    // 默认渲染函数
    const defaultRenderItem = (item, index) => (
        <div
            key={item.id || index}
            style={{
                cursor: 'pointer',
                padding: '16px 0',
                borderBottom: index < localData.length - 1 ? '1px solid #f0f0f0' : 'none',
                transition: 'all 0.3s ease'
            }}
            onClick={() => onItemClick && onItemClick(item, index)}
            onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = '#f8f9fa';
            }}
            onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = 'transparent';
            }}
        >
            <div style={{
                display: 'flex',
                alignItems: 'flex-start',
                gap: '16px'
            }}>
                {/* 文章内容 */}
                <div style={{ flex: 1, minWidth: 0 }}>
                    {/* 文章标题 */}
                    <div style={{
                        fontSize: '16px',
                        fontWeight: 'bold',
                        color: '#333',
                        marginBottom: '8px',
                        lineHeight: '1.4',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap'
                    }}>
                        {item.title}
                    </div>
                    
                    {/* 文章摘要 */}
                    <div style={{
                        fontSize: '14px',
                        color: '#666',
                        lineHeight: '1.4',
                        marginBottom: '12px',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        display: '-webkit-box',
                        WebkitLineClamp: 2,
                        WebkitBoxOrient: 'vertical',
                        maxHeight: '2.8em'
                    }}>
                        {item.summary}
                    </div>
                    
                    {/* 文章信息 */}
                    <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        fontSize: '12px',
                        color: '#999'
                    }}>
                        {/* 左侧信息 */}
                        <div style={{ 
                            display: 'flex', 
                            alignItems: 'center', 
                            gap: '16px',
                            flexWrap: 'wrap'
                        }}>
                            <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                <UserOutline style={{ fontSize: '12px' }} />
                                {item.author}
                            </span>
                            <span>{item.publishTime}</span>
                            <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                <span style={{ fontSize: '10px' }}>👁️</span>
                                {item.readCount}
                            </span>
                        </div>
                        
                        {/* 右侧标签 */}
                        <div style={{
                            display: 'flex',
                            gap: '6px'
                        }}>
                            {item.tags?.slice(0, 2).map((tag, tagIndex) => (
                                <span
                                    key={tagIndex}
                                    style={{
                                        backgroundColor: '#f0f0f0',
                                        color: '#666',
                                        padding: '2px 8px',
                                        borderRadius: '12px',
                                        fontSize: '10px',
                                        whiteSpace: 'nowrap'
                                    }}
                                >
                                    {tag}
                                </span>
                            ))}
                        </div>
                    </div>
                </div>
                
                {/* 文章图片 */}
                <div style={{
                    width: '80px',
                    height: '60px',
                    borderRadius: '8px',
                    overflow: 'hidden',
                    flexShrink: 0
                }}>
                    <img
                        src={item.image}
                        alt={item.title}
                        style={{
                            width: '100%',
                            height: '100%',
                            objectFit: 'cover'
                        }}
                    />
                </div>
            </div>
        </div>
    );

    return (
        <div 
            ref={containerRef}
            className={className}
            style={{
                height: containerHeight,
                overflow: containerHeight !== "auto" ? "auto" : "visible",
                position: 'relative',
                ...style
            }}
            onTouchStart={handleTouchStart}
            onTouchMove={handleTouchMove}
            onTouchEnd={handleTouchEnd}
        >
            {/* 下拉刷新指示器（占位在内容上方，不遮挡列表） */}
            {pullToRefresh && (
                <div
                    style={{
                        height: localRefreshing ? 60 : Math.max(0, Math.min(pullDistance, 60)),
                        transition: isPulling ? 'none' : 'height 0.2s ease',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        backgroundColor: (localRefreshing || pullDistance > 0) ? '#f8f9fa' : 'transparent'
                    }}
                >
                    {localRefreshing ? (
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <SpinLoading color="primary" size="16px" />
                            <span style={{ fontSize: '14px', color: '#666' }}>刷新中...</span>
                        </div>
                    ) : (
                        pullDistance > 0 && (
                            <span style={{ fontSize: '14px', color: '#666' }}>
                                {pullDistance >= 40 ? '松开刷新' : '下拉刷新'}
                            </span>
                        )
                    )}
                </div>
            )}

            {/* 列表内容 */}
            <div style={{ marginBottom: '20px' }}>
                {localData.map((item, index) => 
                    renderItem ? renderItem(item, index) : defaultRenderItem(item, index)
                )}
            </div>
            
            {/* 加载更多 */}
            {localHasMore && (
                <div
                    ref={loadingRef}
                    style={{
                        textAlign: 'center',
                        padding: '16px 0',
                        color: '#999',
                        cursor: loadError ? 'pointer' : (localLoadingMore ? 'default' : 'pointer'),
                        borderTop: '1px solid #f0f0f0',
                        backgroundColor: loadError ? '#fff2f0' : 'transparent',
                        borderRadius: loadError ? '8px' : '0',
                        margin: loadError ? '8px' : '0'
                    }}
                    onClick={loadError ? loadMore : (!localLoadingMore ? loadMore : undefined)}
                >
                    {localLoadingMore ? (
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' }}>
                            <SpinLoading color="primary" size="16px" />
                            <span>{loadingText}</span>
                        </div>
                    ) : loadError ? (
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' }}>
                            <span style={{ color: '#ff4d4f' }}>加载失败，点击重试</span>
                            <span style={{ fontSize: '12px' }}>🔄</span>
                        </div>
                    ) : (
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' }}>
                            <span>{loadMoreText}</span>
                            <span style={{ fontSize: '12px' }}>↑</span>
                        </div>
                    )}
                </div>
            )}
            
            {!localHasMore && localData.length > 0 && (
                <div style={{
                    textAlign: 'center',
                    padding: '16px 0',
                    color: '#999',
                    borderTop: '1px solid #f0f0f0'
                }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' }}>
                        <span>{noMoreText}</span>
                        <span style={{ fontSize: '12px' }}>📄</span>
                    </div>
                </div>
            )}
            
            {/* 空状态 */}
            {!localLoading && !localRefreshing && localData.length === 0 && (
                <div style={{
                    textAlign: 'center',
                    padding: '40px 20px',
                    color: '#999'
                }}>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '12px' }}>
                        <span style={{ fontSize: '48px' }}>📋</span>
                        <span>{emptyText}</span>
                        {pullToRefresh && (
                            <span style={{ fontSize: '12px', color: '#ccc' }}>下拉刷新试试</span>
                        )}
                    </div>
                </div>
            )}

            {/* 初始加载状态 */}
            {localLoading && localData.length === 0 && (
                <div style={{
                    textAlign: 'center',
                    padding: '40px 20px',
                    color: '#999'
                }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' }}>
                        <SpinLoading color="primary" size="20px" />
                        <span>加载中...</span>
                    </div>
                </div>
            )}

            {/* 全局刷新遮罩层（覆盖列表区域） */}
            {localRefreshing && (
                <div style={{
                    position: 'absolute',
                    inset: 0,
                    backgroundColor: 'rgba(255,255,255,0.7)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 3
                }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                        <SpinLoading color="primary" size="24px" />
                        <span style={{ fontSize: '14px', color: '#666' }}>刷新中...</span>
                    </div>
                </div>
            )}
        </div>
    );
};

export default VirtualList;
